package com.zjj.jpa.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjj.jpa.dao.UserDao;
import com.zjj.jpa.entity.User;

@RestController
public class UserController {

	@Autowired
	private UserDao userDao;
	
	@GetMapping("/user")
	public Page<User> list(@RequestParam Integer page, @RequestParam Integer size) {
		if (page != 0) {
			page = page - 1;
		}
		Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "id");  
		return userDao.findAll(pageable);
	}
	
	@GetMapping("/user/{id}")
	public User userInfo(@PathVariable Integer id) {
		return userDao.findOne(id);
	}
	
	@PostMapping("/user")
	public User addUser(@RequestParam String name, @RequestParam Integer age) {
		User user = new User();
		user.setAge(age);
		user.setName(name);
		return userDao.save(user);
	}

	@PutMapping("/user/{id}")
	public boolean updateUser(@PathVariable Integer id, @RequestParam String name, @RequestParam Integer age) {
		int resultStatus = userDao.updateUserById(name, age, id);
		return resultStatus >= 1; 
	}
	
	@DeleteMapping("/user/{id}")
	public void deleteUser(@PathVariable Integer id) {
		userDao.delete(id);
	}
}
